# -*- coding: utf-8 -*-

import web900.facade as facade 
import web900.httpUtils as httpUtils


from mod_python import util, apache




def handle_error_in_apache(f):
    
    def new_f( **kwargs):
        req = kwargs['req']
        try:
            return f( **kwargs)
        except Exception, e:
            req.log_error("unexpected failure on %s : %s" % (f.__name__, str(e)), apache.APLOG_CRIT)            
            submit_issue()     
            _display_message_error(req)       
            req.internal_redirect("/web900/index.psp")
        except Error, e:
            req.log_error("unexpected failure on %s : %s" % (f.__name__, str(e)), apache.APLOG_CRIT)            
            submit_issue()
            _display_message_error(req)
            req.internal_redirect("/web900/index.psp")        
    return new_f

def _getLogguedUser(req):
    return httpUtils.getLoguedUser(req)

def _setLogguedUser(req, user):
    httpUtils.setLoguedUser(req, user)

@handle_error_in_apache
def logout(req):
    httpUtils.logout(req)
    _display_message_info(req, "You have been log off")
    req.internal_redirect("/web900/signin.psp")

@handle_error_in_apache
def signup(req, login, password, password2):
    """
    Create a new account
    """
    # verify that the 2 password are the same
    if password != password2 :
        req.log_error("cannot create account, password mismatch", apache.APLOG_INFO)
        _display_message_error(req, "Password mismatch")
        req.internal_redirect("/web900/signup.psp")
        return        
    
    user = facade.signup(login, password)
    if user is None :
        req.log_error("cannot create account, user probably already exists", apache.APLOG_NOTICE)
        _display_message_error(req, "Account not created, you may choose another login")
        req.internal_redirect("/web900/signup.psp")        
    else:   
        req.log_error("account %s created" % (login,), apache.APLOG_INFO)
        _setLogguedUser(req, user)    
        _display_message_info(req,"Account created, Welcome")    
        req.internal_redirect("/web900/index.psp")  


@handle_error_in_apache
def revoke_guess(req,guess):
    """
    Delete a guess
    """
    user = _getLogguedUser(req)
    facade.revoke_guess(user, guess)
    _display_message_info(req, message="guess deleted")
    req.internal_redirect("/web900/invite.psp")

@handle_error_in_apache
def invite(req, login, password, password2):
    """
    Create guess account
    """
    # verify that the 2 password are the same
    if password != password2 :
        req.log_error("cannot create account, password mismatch", apache.APLOG_INFO)
        _display_message_error(req, "Password mismatch")
        req.internal_redirect("/web900/invite.psp")
        return        
    
    user = _getLogguedUser(req)
    guess = facade.addGuess(user, login, password)
    if guess is None :
        req.log_error("cannot create guess account, user probably already exists", apache.APLOG_NOTICE)
        _display_message_error(req, "Account not created, you may choose another login")
        req.internal_redirect("/web900/invite.psp")       
    else:   
        req.log_error("guess account %s created" % (login,), apache.APLOG_INFO)        
        _display_message_info(req,"Guess account created")    
        req.internal_redirect("/web900/invite.psp") 

@handle_error_in_apache
def signin(req, login, password):
    """
    Log in with an existing account
    """    
    req.log_error("attemp signing with %s, %s" % (login, password), apache.APLOG_DEBUG)
    user = facade.signin(login, password)
    if user:
        req.log_error("login %s succesfull" % (login,), apache.APLOG_INFO)
        _setLogguedUser(req, user) # this is a pure http stuff    
        _display_message_info(req,"Welcome %s" % (user.name,))
        util.redirect(req, "/web900/index.psp")
    else:
        req.log_error("No such user found or bad password", apache.APLOG_NOTICE)        
        _display_message_error(req, "Logon failed")
        req.internal_redirect("/web900/signin.psp")        
 
@handle_error_in_apache
def apply_settings(req):
    """
    Modify user account settings
    """
    req.log_error("apply settings....", apache.APLOG_DEBUG)
    if req.form.has_key("settings_account"):
        req.log_error("apply settings for account...", apache.APLOG_DEBUG)
        user = _getLogguedUser(req)
        password = req.form.get("password",user.password)
        password2 = req.form.get("password2", user.password)
        if  password != password2 :
            req.log_error("cannot update account, password mismatch", apache.APLOG_NOTICE)
            _display_message_error(req, "Password mismatch")
            req.internal_redirect("/web900/settings.psp")  
        else:
            user = facade.update_user(user, req.form.get("name", user.name), password)
            _setLogguedUser(req, user)
            req.internal_redirect("/web900/settings.psp")
    elif req.form.has_key("settings_key"):
        req.log_error("changing api key...")        
        user = _getLogguedUser(req)
        facade.change_api_key(user)
        req.internal_redirect("/web900/settings.psp")        
    else:
        req.log_error("unknown command", apache.APLOG_ERR)
        req.internal_redirect("/web900/settings.psp")
        


def submit_issue():
        pass
#    type, value,tb = sys.exc_info()             
#    self.__default_exception_handler(type, value, tb, gtk_sync = gtk_sync)
#
#    try:
#        issues_client = gdata.projecthosting.client.ProjectHostingClient()
#        issues_client.client_login(username, password,"zourite", "code")
#        versionInstance = version.getInstance()
#        versionStr = versionInstance.getVersion()
#        revisionStr = versionInstance.getRevision()
#        labels = ['Type-Defect', 'Priority-High', 'Version-' + versionStr, 'Revision-' + revisionStr]
#        issues_client.add_issue("zourite", title, description, "tbressure", labels=labels)
#    except:                    
#        self.show_banner_information("failed to send issue")
#        logging.exception("Failed to report the previous issue due to")
#    else:
#        self.show_banner_information("issue sent")
 



        
@handle_error_in_apache
def push_status(req, key, **kwargs):
    user = facade.getUserFromApiKey(key)
    data = {}
    for name in req.form.keys():
        if name != 'key' : 
            value = req.form.getlist(name)[0]
            data[name] = value

    facade.push_status(user, data)
    return ""

@handle_error_in_apache
def push_location(req, lat ,long, fix, key, **kwargs): 
    user = facade.getUserFromApiKey(key)
    facade.push_location(user, lat, long, fix)    
    return ""  
 
@handle_error_in_apache
def push_address_book(req, key, **kwargs):
    user = facade.getUserFromApiKey(key)        
    facade.push_address_book(user, **kwargs)  
    return ""      

@handle_error_in_apache
def poll_command(req, key, **kwargs):
    user = facade.getUserFromApiKey(key) 
    return facade.poll_command(user)

@handle_error_in_apache
def delete_uploaded_file(req, key, filename, filekey, **kwargs):
    """
    The device use this action to delete an uploaded file
    after it have successfully download it 
    """
    user = facade.getUserFromApiKey(key) 
    facade.delete_uploaded_file(user, filename, filekey)
    return ""
    
    
@handle_error_in_apache
def shutdown(req):
    user = _getLogguedUser(req) 
    facade.shutdown(user)
    req.internal_redirect("/web900/index.psp")

#def add_cmd_listener(req):
#    last_noise = time.time();
#    while True:        
#        listing = os.listdir(N900_COMMAND_DIR)
#        for f in listing :
#            filepath = os.path.join(N900_COMMAND_DIR, f)
#            if os.path.isfile(filepath):
#                req.connection.write("1") 
#                break
#        else:
#            now = time.time()
#            if  now - last_noise > 60:
#                req.connection.write("0")    
#                last_noise = now               
#            time.sleep(1)  


@handle_error_in_apache
def ring_my_bell(req):
    user = _getLogguedUser(req)   
    facade.ring_my_bell(user)
    _display_message_info(req,"the phone will soon ring")
    req.internal_redirect("/web900/index.psp")

@handle_error_in_apache
def call(req, number):
    user = _getLogguedUser(req)   
    facade.call(user, number)
    _display_message_info(req)
    req.internal_redirect("/web900/index.psp")

def _display_message_info(req, message="Command succesful"):
    req.form.add_field("message_info",message)
    


def _display_message_error(req, message="Command Failure"):
    req.form.add_field("message_error",message)    

@handle_error_in_apache
def lock_device(req):
    user = _getLogguedUser(req)   
    facade.lock_device(user)
    _display_message_info(req)    
    util.redirect(req,"/web900//index.psp")

@handle_error_in_apache
def unlock_device(req):
    user = _getLogguedUser(req)
    facade.unlock_device(user)
    _display_message_info(req)    
    util.redirect(req,"/web900//index.psp")

@handle_error_in_apache            
def open_url(req, url):
    user = _getLogguedUser(req)
    facade.open_url(user, url)
    _display_message_info(req)    
    util.redirect(req,"/web900//index.psp")


#@handle_error_in_apache
def send_im(req, content):
    user = _getLogguedUser(req)
    facade.send_im(user, content)
    _display_message_info(req)
    req.internal_redirect("/web900/index.psp")    

    
@handle_error_in_apache
def send_sms(req, recipient, content):
    user = _getLogguedUser(req)
    facade.send_sms(user, recipient, content)
    _display_message_info(req)
    req.internal_redirect("/web900/index.psp")       




    
@handle_error_in_apache    
def upload_file(req, **kwargs):
    """
    This action is used to push a file on the device.
    """
        
    user = _getLogguedUser(req)
    field = req.form.getfirst('file')    
    facade.upload_file(user, field.file, field.filename)
    _display_message_info(req)    
    util.redirect(req,"/web900/index.psp")
    

#from mod_python import apache
#
#PUSH_FLAG = False
#
#def connectionhandler(conn):
#
#    while True:                
#        time.sleep(1)
#        if PUSH_FLAG :
#           conn.write("WAKEUPWAKEUWAKEUP")
#           PUSH_FLAG = False
#    return apache.OK

    